﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using Object = UnityEngine.Object;

public class CreateUIRooot : EditorWindow {

    string w = "1920";
    string h = "1080";

    [MenuItem(itemName: "EzFreamWork/创建UI根节点",isValidateFunction:true)]
    static bool ValidateUIRoot()
    {
        return GameObject.Find("RootUI") == null;
    }

    private void OnGUI()
    {
        GUILayout.BeginHorizontal();
        GUILayout.Label("设置Canvas分辨率：",GUILayout.Width(120));
        GUILayout.Label("长：", GUILayout.Width(20));
        w = GUILayout.TextField(w);
        GUILayout.Label("宽：", GUILayout.Width(20));
        h = GUILayout.TextArea(h);
        GUILayout.EndHorizontal();
        if (GUILayout.Button("生成RootUI"))
        {
            SetUp(w, h);
            Close();
        }
    }

    [MenuItem(itemName: "EzFreamWork/创建UI根节点 &u", isValidateFunction: false)]
    static void MenuItem()
    {
        var window = GetWindow<CreateUIRooot>();
        window.Show();
    }
    /// </summary>
    /// <param name="w"></param>
    /// <param name="h"></param>
    private static void SetUp(string w,string h)
    {
        Debug.Log("MenuItem");
        GameObject RootUI = new GameObject("RootUI");
        RootUI.transform.position = Vector3.zero;
        RootUI.layer = LayerMask.NameToLayer("UI");
        GameObject MainMenuCanvas = new GameObject("MainMenuCanvas");
        MainMenuCanvas.layer = LayerMask.NameToLayer("UI");
        GameObject ESystem = new GameObject("EventSystem");
        MainMenuCanvas.transform.parent = RootUI.transform;
        MainMenuCanvas.transform.localPosition = Vector3.zero;
        ESystem.transform.parent = RootUI.transform;
        ESystem.AddComponent<EventSystem>();
        ESystem.AddComponent<StandaloneInputModule>();
        MainMenuCanvas.AddComponent<Canvas>().renderMode = RenderMode.ScreenSpaceOverlay;
        CanvasScaler canvasScaler = MainMenuCanvas.AddComponent<CanvasScaler>();
        canvasScaler.uiScaleMode = CanvasScaler.ScaleMode.ScaleWithScreenSize;
        canvasScaler.referenceResolution = new Vector2(Convert.ToInt32(w), Convert.ToInt32(h));
        MainMenuCanvas.AddComponent<GraphicRaycaster>();

        GameObject bgobj = new GameObject("Bg");
        RectTransform rectBG = bgobj.AddComponent<RectTransform>();
        rectBG.position = Vector3.zero;
        rectBG.sizeDelta = new Vector2(Convert.ToInt32(w), Convert.ToInt32(h));
        rectBG.SetParent(MainMenuCanvas.transform);

        GameObject panel = new GameObject("Panels");
        RectTransform rectPanel = panel.AddComponent<RectTransform>();
        rectPanel.position = Vector3.zero;
        rectPanel.sizeDelta = new Vector2(Convert.ToInt32(w), Convert.ToInt32(h));
        rectPanel.SetParent(MainMenuCanvas.transform);

        GameObject commonobj = new GameObject("Common");
        RectTransform rectCommonObj = commonobj.AddComponent<RectTransform>();
        rectCommonObj.position = Vector3.zero;
        rectCommonObj.sizeDelta = new Vector2(Convert.ToInt32(w), Convert.ToInt32(h));
        rectCommonObj.SetParent(MainMenuCanvas.transform);

        GameObject popUI = new GameObject("PopUI");
        popUI.AddComponent<RectTransform>().sizeDelta = new Vector2(Convert.ToInt32(w), Convert.ToInt32(h)); 
        popUI.transform.SetParent(MainMenuCanvas.transform);
        popUI.transform.position = Vector3.zero;

        RootUI rootUI = RootUI.AddComponent<RootUI>();
        rootUI.MainMenuCanvas = MainMenuCanvas;
        rootUI.Bg = bgobj;
        rootUI.Panels = panel;
        rootUI.Common = commonobj;
        rootUI.PopUI = popUI;

        var uirootScriptSerializedobj = new SerializedObject(rootUI);
        uirootScriptSerializedobj.ApplyModifiedPropertiesWithoutUndo();
        CreatePrefab(RootUI);
    }

#if UNITY_2017

#endif
#if UNITY_2018_3 || UNITY_2019
    static void CreatePrefab(GameObject obj)
    {
        // Keep track of the currently selected GameObject(s)

        string localPath = "Assets/Resources/UI/" + obj.name + ".prefab";
        if (Directory.Exists("Assets/Resources/UI"))
        {

        }
        else
        {
            Directory.CreateDirectory("Assets/Resources/UI");
        }
        localPath = AssetDatabase.GenerateUniqueAssetPath(localPath);
        PrefabUtility.SaveAsPrefabAssetAndConnect(obj, localPath, InteractionMode.UserAction);
    }
#else
    //Creates a new menu (Examples) with a menu item (Create Prefab)
    static void CreatePrefab(GameObject obj)
    {
        string localPath = "Assets/Resources/UI/" + obj.name + ".prefab";
        if (Directory.Exists("Assets/Resources/UI"))
        {

        }
        else
        {
            Directory.CreateDirectory("Assets/Resources/UI");
        }

        if (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject)))
        {
            if (EditorUtility.DisplayDialog("Are you sure?",
                    "The prefab already exists. Do you want to overwrite it?",
                    "Yes",
                    "No"))
            {
                CreateNew(obj, localPath);
            }
        }
        else
        {
            Debug.Log(obj.name + " is not a prefab, will convert");
            CreateNew(obj, localPath);
        }
    }

    static bool ValidateCreatePrefab()
    {
        return Selection.activeGameObject != null;
    }

    static void CreateNew(GameObject obj, string localPath)
    {
        Object prefab = PrefabUtility.CreateEmptyPrefab(localPath);
        PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);
    }
#endif


    /// <summary>
    /// 从新打开项目
    /// </summary>
    [MenuItem("EzFreamWork/ReopenProject &r")]
    static void DoReopenProject()
    {
        EditorApplication.OpenProject(Application.dataPath.Replace("Assets",string.Empty));
    }
}
